package cn.wolfcode.crm.shrio.filter;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * 自定义认证过滤器 重写这个两个方法 使得登录成功或者失败后返回Json数据给前端
 */
@Component("crmAuthenticationFilter")
public class AjaxAuthenticationFilter extends FormAuthenticationFilter {
    //登录成功 shiro执行的方法
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        JsonResult result = new JsonResult("登录成功", true);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(JSON.toJSONString(result));
        return false;
    }
    //登录失败 shiro执行的方法
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        JsonResult jsonResult = new JsonResult();
        jsonResult.setSuccess(false);
        if (e instanceof UnknownAccountException) {
            jsonResult.setMsg("账号错误");
        } else if (e instanceof IncorrectCredentialsException) {
            jsonResult.setMsg("密码错误");
        } else {
            jsonResult.setMsg("系统繁忙,稍后重试");
        }
        try {
            response.getWriter().print(JSON.toJSONString(jsonResult));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}

